package eureka.consumer.redissonlock.review.impl;

import eureka.consumer.redissonlock.interfaces.DistributedLockCallback;
import eureka.consumer.redissonlock.interfaces.DistributedLockTemplate;
import eureka.consumer.redissonlock.review.lockinter.DistributeLockTemplate;
import eureka.consumer.redissonlock.review.lockinter.LockCallback;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author RenPu
 * @Date 2023/10/7 16:00
 * @Version 1.0
 * @Description:分布式锁实现得具体逻辑类
 **/
public class RedissonDistributeLockImpl implements DistributeLockTemplate {

    //1：设置超时时间以及单位
    //2：获取RedissonClient,编写分布式锁得获取以及释放

    private static final long DEFAULT_TIMEOUT=5;

    private static final TimeUnit DEFAULT_UNIT=TimeUnit.SECONDS;

    private RedissonClient redissonClient;


    public RedissonDistributeLockImpl(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public RedissonDistributeLockImpl() {
    }

    /**
     * 获取默认超时时间以及单位得布式锁
     * @param callback
     * @param <T>
     * @return
     */
    @Override
    public <T> T getLock(LockCallback<T> callback) {
        return getLock(callback,DEFAULT_TIMEOUT,DEFAULT_UNIT);
    }



    /**
     *  获取自定义超时时间以及单位得分布式锁
     * @param callback
     * @param leaseTime
     * @param timeUnit
     * @param <T>
     * @return
     */
    @Override
    public <T> T getLock(LockCallback<T> callback, long leaseTime, TimeUnit timeUnit) {
        RLock lock=null;
        try{
           lock = redissonClient.getLock(callback.getLockName());
           lock.lock(leaseTime,timeUnit);
           return callback.getproess();
       }finally {
            if(!Objects.isNull(lock)){
                lock.unlock();
            }
        }
    }


    public RedissonClient getRedissonClient() {
        return redissonClient;
    }

    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

}
